package com.tianji.promotion.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.constants.RedisConstant;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.ExchangeCode;
import com.tianji.promotion.domain.query.CodeQuery;
import com.tianji.promotion.domain.vo.ExchangeCodeVO;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.tianji.promotion.util.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.constants.PromotionConstants.COUPON_CODE_MAP_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author xjs
 */
@Service
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Async("generateExchangeCodeExecutor")
    @Override
    public void asyncGenerateExchangeCode(Coupon coupon) {
        Long couponId = coupon.getId();
        Integer totalNum = coupon.getTotalNum();
        // 先占位
        Long maxValue = redisTemplate.opsForValue().increment(RedisConstant.EXCHANGE_CODE_PREFIX, totalNum);
        List<ExchangeCode> codeList = new ArrayList<>();
        for(int i=0; i<totalNum; i++){
            long serialNum = maxValue - totalNum + i + 1;
            String code = CodeUtil.generateCode(serialNum, couponId);
            ExchangeCode ec = new ExchangeCode();
            ec.setId((int)serialNum);
            ec.setCode(code);
            ec.setType(1);
            ec.setExchangeTargetId(couponId);
            // 兑换码的有效期等于优惠券的领用结束时间
            ec.setExpiredTime(coupon.getIssueEndTime());
            ec.setStatus(1);
            codeList.add(ec);
        }
        this.saveBatch(codeList);
    }

    @Override
    public PageDTO<ExchangeCodeVO> queryCodePage(CodeQuery query) {
        // 1.分页查询兑换码
        Page<ExchangeCode> page = lambdaQuery()
                .eq(ExchangeCode::getStatus, query.getStatus())
                .eq(ExchangeCode::getExchangeTargetId, query.getCouponId())
                .page(query.toMpPage());
        // 2.返回数据
        return PageDTO.of(page, c -> new ExchangeCodeVO(c.getId(), c.getCode()));
    }

    @Override
    public boolean updateExchangeMark(long serialNum, boolean mark) {
        Boolean boo = redisTemplate.opsForValue().setBit(COUPON_CODE_MAP_KEY, serialNum, mark);
        return boo != null && boo;
    }

}
